package com.imay.live.activity.dynamics;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.imay.base.helper.NetworkHelper;
import com.imay.live.R;
import com.imay.live.adapter.RepostAdapter;
import com.imay.live.fragment.dynamics.DynamicsParams;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.LocationHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.model.FeedModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.ResultCode;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.imay.base.util.SpannableStringUtils.getBuilder;

/**
 * 转发页面
 * Created by chan on 2017/4/14.
 */

public class RepostActivity extends DynamicsFeedActivity implements View.OnClickListener {

    private final static String FEEDKEY = "feed_key";
    private TextView mRepostTitle, mRepostContentDes, mRepostDes;
    private FeedModel feed;
    private Context mContext;


    public static void startActivity(Context activity, FeedModel feed) {
        Intent intent = new Intent(activity, RepostActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable(FEEDKEY, feed);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_repost;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        com.imay.live.utils.ViewUtil.setForgroundRadius($(R.id.ll_content));
        mContext = this;

        feedStauts = STATUS_REPOST;

        setTitle(getString(R.string.str_repost_title));

        initWidget();
        initDatas();
        initListener();
    }


    private void initWidget() {
        setRightView();
        mRepostTitle = $(R.id.tv_repost_content_title);
        mRepostContentDes = $(R.id.tv_repost_content_des);
        mRepostDes = $(R.id.tv_repost_des);
        mCountText = $(R.id.tv_repost_count);

        mRepostAt = $(R.id.iv_repost_at);
        mRepostJin = $(R.id.iv_repost_jin);
        tv_familyId_status = $(R.id.tv_familyId_status);

        loadView = $(R.id.lv_repost);
        loadView.setVisibility(View.GONE);

        mEtContent = $(R.id.et_repost);
        mEtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});

        mCountText.setText(count + "");

        // 初始化RecyclerView
        mRecyclerView = $(R.id.rcv_repost);
        WrapContentLinearLayoutManager layoutManager
                = new WrapContentLinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new RepostAdapter();
        mAdapter.bindToRecyclerView(mRecyclerView);
        mRecyclerView.setHasFixedSize(true);
    }


    // 初始化数据
    private void initDatas() {
        Bundle b = getIntent().getExtras();
        feed = b.getParcelable(FEEDKEY);
        if (feed == null) {
            return;
        }

        FeedModel feedModel;
        if (feed.getRepostedFeed() != null && feed.getUser() != null) {
            feedModel = feed.getRepostedFeed();
            StringBuffer stringBuffer = new StringBuffer(" //");
            stringBuffer.append(getString(R.string.str_dynamics_at_text, feed.getUser().getNick()));
            stringBuffer.append(" " + feed.getMsg());

            String des1 = stringBuffer.toString();
            if (TextUtils.isEmpty(des1)) {
                mRepostDes.setVisibility(View.GONE);
            } else {
                mRepostDes.setVisibility(View.VISIBLE);
                set(feed, des1, mRepostDes);
            }


            count = count - stringBuffer.length();
            mEtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(count)});
            mCountText.setText(count + "");
        } else {
            feedModel = feed;
            mRepostDes.setVisibility(View.GONE);
        }

        internalPublic = feed.getInternalPublic();
        familyId = feed.getFamilyId();

        if (familyId != 0 && internalPublic != 0) {
            tv_familyId_status.setText(R.string.str_feed_menu_family);
        } else {
            tv_familyId_status.setText(R.string.str_feed_menu_open);
        }

        //标题
        if (feedModel.getUser() != null) {
            SpannableStringBuilder title = getBuilder(getString(R.string.str_repost_des_title, feedModel.getUser().getNick())).setBold().create();
            mRepostTitle.setText(title);
        }

        String des = feedModel.getMsg();
        set(feedModel, des, mRepostContentDes);

        if (feedModel.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) {
            $(R.id.iv_repost_content_ico).setVisibility(View.INVISIBLE);
            GlideUtil.loadRectangleImage(((ImageView) $(R.id.iv_repost_img)), feedModel.getImgUrl(), R.dimen.size_4dp, R.drawable.shape_placeholder_2);
        } else if (feedModel.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) {
            $(R.id.iv_repost_content_ico).setVisibility(View.VISIBLE);
            GlideUtil.loadRectangleImage((ImageView) $(R.id.iv_repost_img), UrlHelper.getVideoThumbUrl(feedModel.getVideoUrl()), R.dimen.size_4dp, R.drawable.shape_placeholder_2);
        }
    }

    @Override
    protected void initListener() {
        super.initListener();

        mRepostAt.setOnClickListener(this);
        mRepostJin.setOnClickListener(this);
        mRepostDes.setOnClickListener(this);
        mCountText.setOnClickListener(this);

        mRightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!NetworkHelper.getInstance().hasConnection()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                if (!SensitiveWordFilterManager.getInstance().hasSensitiveWord(mEtContent)) {
                    String msg = mEtContent.getText().toString() + mRepostDes.getText().toString();
                    FeedModel feedModel;
                    if (feed.getRepostedFeed() != null) {
                        feedModel = feed.getRepostedFeed();
                    } else {
                        feedModel = feed;
                    }
                    // 创建动态
                    if (msg.length() > 100) {
                        ToastUtil.show(mContext, R.string.str_dynamics_comment_note);
                        return;
                    }
                    LocationHelper helper = LocationHelper.getInstance();
                    DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getString(R.string.str_realse_loading));
                    createFeed(feedModel.getImgUrl(), feedModel.getVideoUrl(), msg, helper.getCity(), Long.toString((long) (helper.getLongitude() * 1000000L)), Long.toString((long) (helper.getLatitude() * 1000000L)), feedModel.getFeedId(), familyId);
                } else {
                    ToastUtil.show(mContext, R.string.sensitive_comment);
                }
            }
        });
    }

    /**
     * 富文本
     *
     * @param item
     * @param des
     * @param mContentDes
     */
    private void set(FeedModel item, String des, TextView mContentDes) {
        Pattern pattern = Pattern.compile("@([^@#\\s]+)|#([^@#\\s]+)");
        Matcher matcher = pattern.matcher(des);

        List<UserModel> userAtBeans = item.getAtUsers();
        List<String> labels = item.getLabels();

        if (!TextUtils.isEmpty(des) && !des.equals("(null)")) {
            SpannableString string = new SpannableString(des);
            int start;
            int end = 0;
            while (matcher.find(end)) {
                boolean c = false;
                start = matcher.start();
                end = matcher.end();
                if (userAtBeans != null && !userAtBeans.isEmpty()) {
                    for (UserModel userBean : userAtBeans) {
                        if (userBean != null) {
                            String nick = getString(R.string.str_dynamics_at_text, userBean.getNick());
                            if (matcher.group().equals(nick)) {
                                string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_30)), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                                c = true;
                                break;
                            }
                        }
                    }
                } else {
                    if (feed.getUser() != null) {
                        String userNick = getString(R.string.str_dynamics_at_text, feed.getUser().getNick());
                        if (matcher.group().equals(userNick)) {
                            string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_30)), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            c = true;
                        }
                    }
                }

                // 防止循环操作相同的
                if (c) {
                    continue;
                }

                if (labels != null && !labels.isEmpty()) {
                    for (String label : labels) {
                        String labelText = getString(R.string.str_dynamics_jin_text, label);
                        if (matcher.group().equals(labelText)) {
                            string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_30)), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            break;
                        }
                    }
                }
            }

            mContentDes.setText(string);
            mContentDes.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
}
